package 网络.TCP;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {
    public static void main(String[] args) throws Exception{
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("服务器启动成功");
        // 阻塞等待客户端连接
        Socket clientSocket = serverSocket.accept();
        System.out.println("Accepted connection from " + clientSocket.getInetAddress());

        // 通过IO流获取客户端发送的消息
        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
        // 接收消息
        String message = in.readLine();
        System.out.println("Received message: " + message);

        // 服务端回复客户端发送的消息
        out.println("Echo: " + message);

        clientSocket.close();
        serverSocket.close();
    }
}
